﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.IO.IsolatedStorage;
using System.Xml.Linq;
using System.Linq;
using System.IO;
using System.Collections.Generic;

namespace ActivityTracker.Library
{
    public class Category
    {
        #region Global

        IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication();
        IsolatedStorageFileStream isoStream;
        XDocument xdoc;
        Actvity objActivity = new Actvity();
        Schedules objSchedules = new Schedules();

        #endregion

        public void SaveDefaultCategories()
        {
            try
            {
                if (!isoStore.FileExists("ActivityTracker/Categories.xml"))
                {
                    Uri uri = new Uri("DefaultData/Categories.xml", UriKind.Relative);
                    xdoc = XDocument.Load(uri.ToString());
                    isoStream = new IsolatedStorageFileStream("ActivityTracker/Categories.xml", FileMode.Create, isoStore);
                    xdoc.Save(isoStream);
                    isoStream.Close();
                }
            }
            catch (Exception ex)
            {
                Exception exNew = new Exception("Exception in SaveDefaultCategories Method In ActivityTracker.Library.Category file\n\n" + ex.Message + " \n\n Stack Trace \n" + ex.StackTrace);
                throw exNew;
            }
        }

        public List<CategoryProp> LoadCategories()
        {
            List<CategoryProp> catlist = new List<CategoryProp>();
            try
            {
                if (isoStore.FileExists("ActivityTracker/Categories.xml"))
                {
                    isoStream = new IsolatedStorageFileStream("ActivityTracker/Categories.xml", FileMode.Open, FileAccess.Read, isoStore);
                    xdoc = XDocument.Load(isoStream);
                    isoStream.Close();
                    var categorylist = from t in xdoc.Descendants("category")
                                       select t;
                    foreach (var cat in categorylist)
                    {
                        CategoryProp catprop = new CategoryProp();
                        catprop.CatId = cat.Attribute("id").Value;
                        catprop.catName = cat.Element("name").Value;
                        catlist.Add(catprop);
                    }
                }
                return catlist;
            }
            catch (Exception ex)
            {
                Exception exNew = new Exception("Exception in LoadCategories Method In ActivityTracker.Library.Category file\n\n" + ex.Message + " \n\n Stack Trace \n" + ex.StackTrace);
                throw exNew;
            }
        }

        public void SaveCheckedCategories(ListBox ListBoxCategories)
        {
            try
            {
                if (isoStore.FileExists("ActivityTracker/TempCategories.xml"))
                    isoStore.DeleteFile("ActivityTracker/TempCategories.xml");
                IEnumerable<DependencyObject> cboxes = CommonClass.GetChildsRecursive(ListBoxCategories);
                List<CategoryProp> catNameList = new List<CategoryProp>();
                foreach (DependencyObject obj in cboxes.OfType<CheckBox>())
                {
                    Type type = obj.GetType();
                    if (type.Name == "CheckBox")
                    {
                        CheckBox cb = obj as CheckBox;
                        if (cb.IsChecked == true)
                            catNameList.Add(new CategoryProp(){CatId=cb.Tag.ToString(), catName=cb.Content.ToString()});
                    }
                }
                foreach (CategoryProp cats in catNameList)
                    saveCategoriesTemp(cats.catName, cats.CatId);
            }
            catch (Exception ex)
            {
                Exception exNew = new Exception("Exception in SelectedCategories Method In ActivityTracker.Library.Category file\n\n" + ex.Message + " \n\n Stack Trace \n" + ex.StackTrace);
                throw exNew;
            }
        }

        public string GetCategoryFromTextBox(Grid PopupGrid)
        {
            string str = string.Empty;
            try
            {
                IEnumerable<DependencyObject> childele = CommonClass.GetChildsRecursive(PopupGrid);
                foreach (DependencyObject obj in childele.OfType<TextBox>())
                {
                    Type type = obj.GetType();
                    if (type.Name == "TextBox")
                    {
                        TextBox tb = obj as TextBox;
                        if (tb.IsReadOnly == false)
                        {
                            str = tb.Text;
                            continue;
                        }
                    }
                }
                return str;
            }
            catch (Exception ex)
            {
                Exception exNew = new Exception("Exception in GetCategoryFromTextBox Method In ActivityTracker.Library.Category file\n\n" + ex.Message + " \n\n Stack Trace \n" + ex.StackTrace);
                throw exNew;
            }
        }

        public void SaveNewCategory(string catName)
        {
            try
            {
                if (isoStore.FileExists("ActivityTracker/Categories.xml"))
                {
                    isoStream = new IsolatedStorageFileStream("ActivityTracker/Categories.xml", FileMode.Open, isoStore);
                    xdoc = XDocument.Load(isoStream);
                    isoStream.Close();
                    int NextId = 1;
                    var singleform = (from f in xdoc.Descendants("category")
                                      orderby (int)f.Attribute("id") descending
                                      select f);
                    foreach (XElement xe in singleform)
                    {
                        NextId = int.Parse(xe.Attribute("id").Value);
                        break;
                    }
                    NextId = NextId + 1;
                    isoStream = new IsolatedStorageFileStream("ActivityTracker/Categories.xml", FileMode.Create, isoStore);
                    xdoc.Root.Add(new XElement("category",
                                       new XAttribute("id", NextId),
                                       new XElement("name", catName)));
                    xdoc.Save(isoStream);
                    isoStream.Close();
                }
            }
            catch (Exception ex)
            {
                Exception exNew = new Exception("Exception in SaveNewCategory Method In ActivityTracker.Library.Category file\n\n" + ex.Message + " \n\n Stack Trace \n" + ex.StackTrace);
                exNew.Data.Add("catName_SaveNewCategory", catName);
                throw exNew;
            }
        }

        public List<CategoryProp> DeleteCategoryConfirmation(ListBox ListBoxCategories, out string ConfirmMessage, out  List<string> actsToDelete)
        {
            List<CategoryProp> catsToDelete = new List<CategoryProp>();
            actsToDelete = new List<string>();
            ConfirmMessage = "";
            try
            {
                IEnumerable<DependencyObject> childele = CommonClass.GetChildsRecursive(ListBoxCategories);
                foreach (DependencyObject obj in childele.OfType<RadioButton>())
                {
                    Type type = obj.GetType();
                    if (type.Name == "RadioButton")
                    {
                        RadioButton cb = obj as RadioButton;
                        if (cb.IsChecked == true)
                        {
                            CategoryProp cli = new CategoryProp();
                            cli.catName = cb.Content.ToString();
                            cli.CatId = cb.Tag.ToString();
                            catsToDelete.Add(cli);
                        }
                    }
                }
                if (catsToDelete.Count > 0)
                {
                    foreach (CategoryProp catgory in catsToDelete)
                    {
                        actsToDelete = objActivity.GetActivitiesCountOncatId(catgory.CatId);
                        if (actsToDelete.Count > 0)
                            if (actsToDelete.Count == 1)
                                ConfirmMessage = actsToDelete.Count + " activity Created using this category.";
                            else
                                ConfirmMessage = actsToDelete.Count + " activities Created using this category.";
                        else
                            ConfirmMessage = "Warning";
                    }
                }
            }
            catch (Exception ex)
            {
                Exception exNew = new Exception("Exception in DeleteCategoryConfirmation Method In ActivityTracker.Library.Category file\n\n" + ex.Message + " \n\n Stack Trace \n" + ex.StackTrace);
                throw exNew;
            }
            return catsToDelete;
        }

        public void DeleteCategories(List<CategoryProp> catsToDelete, List<string> actsToDelete)
        {
            try
            {
                foreach (CategoryProp catgory in catsToDelete)
                {
                    foreach (string actId in actsToDelete)
                    {
                        objSchedules.DeleteSchedulesBasedOnActId(actId);
                        objActivity.DeleteActivity(actId);
                    }
                    DeleteCategory(catgory.CatId);
                }
            }
            catch (Exception ex)
            {
                Exception exNew = new Exception("Exception in DeleteCategories Method In ActivityTracker.Library.Category file\n\n" + ex.Message + " \n\n Stack Trace \n" + ex.StackTrace);
                throw exNew;
            }
        }

        public void DeleteCategory(string catId)
        {
            try
            {
                isoStream = new IsolatedStorageFileStream("ActivityTracker/Categories.xml", FileMode.Open, isoStore);
                xdoc = XDocument.Load(isoStream);
                isoStream.Close();
                (from cat in xdoc.Descendants("category") where cat.Attribute("id").Value == catId select cat).Remove();
                isoStream = new IsolatedStorageFileStream("ActivityTracker/Categories.xml", FileMode.Create, isoStore);
                xdoc.Save(isoStream);
                isoStream.Close();
            }
            catch (Exception ex)
            {
                Exception exNew = new Exception("Exception in DeleteCategoryUsingCatId Method In ActivityTracker.Library.Category file\n\n" + ex.Message + " \n\n Stack Trace \n" + ex.StackTrace);
                exNew.Data.Add("catId_DeleteCategoryUsingCatId", catId);
                throw exNew;
            }
        }

        //savetoisolated
        public void saveCategoriesTemp(string catName, string catid)
        {
            try
            {
                if (isoStore.FileExists("ActivityTracker/TempCategories.xml"))
                {
                    isoStream = new IsolatedStorageFileStream("ActivityTracker/TempCategories.xml", FileMode.Open, isoStore);
                    xdoc = XDocument.Load(isoStream);
                    isoStream.Close();
                    isoStream = new IsolatedStorageFileStream("ActivityTracker/TempCategories.xml", FileMode.Create, isoStore);
                    xdoc.Root.Add(new XElement("catogory", new XAttribute("catid", catid), new XAttribute("catName", catName)));
                    xdoc.Save(isoStream);
                    isoStream.Close();
                }
                else
                {
                    isoStream = new IsolatedStorageFileStream("ActivityTracker/TempCategories.xml", FileMode.Create, isoStore);
                    xdoc = new XDocument(new XDeclaration("1.0", "utf-8", "yes"),
                                new XElement("list",
                                    new XElement("catogory",
                                        new XAttribute("catid", catid),
                                        new XAttribute("catName", catName))));
                    xdoc.Save(isoStream);
                    isoStream.Close();
                }
            }
            catch (Exception ex)
            {
                Exception exNew = new Exception("Exception in saveCategoriesTemp Method In ActivityTracker.Library.Category file\n\n" + ex.Message + " \n\n Stack Trace \n" + ex.StackTrace);
                exNew.Data.Add("catName_saveCategoriesTemp", catName);
                throw exNew;
            }
        }

        public List<CategoryProp> LoadCheckedCategories()
        {
            List<CategoryProp> catlist = new List<CategoryProp>();
            try
            {
                if (isoStore.FileExists("ActivityTracker/TempCategories.xml"))
                {
                    isoStream = new IsolatedStorageFileStream("ActivityTracker/TempCategories.xml", FileMode.Open, isoStore);
                    xdoc = XDocument.Load(isoStream);
                    isoStream.Close();
                    var catList = from t in xdoc.Descendants("catogory")
                                  select t;
                    foreach (var cat in catList)
                    {
                        CategoryProp cat1 = new CategoryProp();
                        cat1.CatId = cat.Attribute("catid").Value;
                        cat1.catName = cat.Attribute("catName").Value;
                        catlist.Add(cat1);
                    }
                }
            }
            catch (Exception ex)
            {
                Exception exnew = new Exception("Exception in LoadCheckedCategories Method In ActivityTracker.Library.Category file.\n\n" + ex.Message + "\n\n Stack Trace:- " + ex.StackTrace);
                throw exnew;
            }
            return catlist;
        }
    }
}
